/**
* @file         utils.h
* @author       David Hu (hmd_hubei_cn@163.com)
* @brief
* @version      0.1
* @date         2024.06.30
* @note
* @copyright    Copyright (c) 2022 DAVID HU All rights reserved. Licensed under
the MIT License (the "License");

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License in the file LICENSE

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.
**/

#ifndef __UTILS_H__
#define __UTILS_H__

#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

// macro definition

// 位操作
#define BIT_SET(x, y)     (x) |= (1 << y)   //将X的Y位置1
#define BIT_CLR(x, y)     (x) &= ~(1 << y)  //将X的Y位置0
#define BIT_GET(x, y)     ((x) >> (y)&1)    //获取某一位
#define BIT_REVERSE(x, y) (x) ^= (1 << y)   //某位取反

// 获取两数中的最大值/最小值
#define MAX(x, y) ((x) > (y) ? (x) : (y))
#define MIN(x, y) ((x) < (y) ? (x) : (y))

// 获取数组元素个数
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))

// 字母大小写转换
#define TO_LOWER(c) ((c) >= 'A' && (c) <= 'Z' ? (c) + 32 : (c))
#define TO_UPPER(c) ((c) >= 'a' && (c) <= 'z' ? (c) - 32 : (c))

// 断言（Assertion）
#define assert(expression) ((void)0)
#ifndef NDEBUG
#undef assert
#define assert(expression) ((expression) ? (void)0 : assert_failed(__FILE__, __LINE__))
#endif

typedef int16_t fixed_t;

#define FIXED_SHIFT 8
#define FLOAT_TO_FIXED(f) ((fixed_t)((f) * (1 << FIXED_SHIFT)))
#define FIXED_TO_FLOAT(f) ((float)(f) / (1 << FIXED_SHIFT))

// data type definition

#define SIZE 100
typedef struct {
    int buffer[SIZE];
    int head;
    int tail;
    int count;
} circular_buffer_t;

// function declaration

float write_hex_to_float(uint32_t number);

uint32_t write_float_to_hex(float number);

void int32_to_byte4(int32_t value, uint8_t *p);

int32_t byte4_to_int32(uint8_t *p);

uint16_t crc16(uint8_t *data, uint32_t len);

uint16_t modbus_crc16(uint8_t *buf_data, uint16_t buf_len);

void cb_push(circular_buffer_t *cb, int data);

int cb_pop(circular_buffer_t *cb);

void assert_failed(const char *file, int line);

int binary_search(int* arr, int size, int target);

fixed_t fixed_multiply(fixed_t a, fixed_t b);

uint16_t big_to_little_endian(uint16_t big_endian);

uint16_t little_to_big_endian(uint16_t little_endian);

void set_bit(uint32_t *data, uint8_t bit);

void clear_bit(uint32_t *data, uint8_t bit);

void toggle_bit(uint32_t *data, uint8_t bit);

uint8_t read_bit(uint32_t data, uint8_t bit);

#ifdef __cplusplus
}
#endif

#endif  //__UTILS_H__
/********************* (C) COPYRIGHT DAVID HU *******END OF FILE ********/
